package analysis

import (
	"encoding/xml"
	"io"
	"irisysFtp/db"
	"strings"
	"time"
)

type Data struct {
	XMLName xml.Name `xml:"Data"`
	Header  Header   `xml:"Header"`
	Counter Counter  `xml:"Counter1-1"`
}

type Header struct {
	Customer     string `xml:"Customer"`
	Camera       int    `xml:"Camera"`
	DateTime     string `xml:"DateTime"`
	TimeZone     string `xml:"TimeZone"`
	TimeZoneStdt string `xml:"TimeZoneStdt"`
}

type Counter struct {
	// 注意：由于这里的元素名是动态的(_08_50, _09_00等)，需要自定义结构体标签和UnmarshalXML方法
	Counters []Record `xml:",any"`
}

type Record struct {
	Time string
	In   int `xml:"In,attr"`
	Out  int `xml:"Out,attr"`
}

func (c *Counter) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for {
		token, err := d.Token()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		switch se := token.(type) {
		case xml.StartElement:
			var r Record
			err = d.DecodeElement(&r, &se)
			if err != nil {
				return err
			}
			r.Time = strings.ReplaceAll(se.Name.Local, "_", "") + "00"
			c.Counters = append(c.Counters, r)
		}
	}

	return nil
}

func winnerCount(analysis *Analysis) ([]*db.DeviceFlow, error) {
	xmlData := strings.Replace(string(analysis.Data), "GB2312", "UTF-8", 1)
	var data Data
	err := xml.Unmarshal([]byte(xmlData), &data)
	if err != nil {
		return nil, err
	}
	deviceId := strings.ReplaceAll(data.Header.Customer, ".t.winneryun.com", "")
	var allDeviceFlow []*db.DeviceFlow
	for _, counter := range data.Counter.Counters {
		dateTime, err := time.ParseInLocation("20060102150405", data.Header.DateTime+counter.Time, time.Local)
		if err != nil {
			return nil, err
		}
		flow := db.DeviceFlow{
			Zone:       "0",
			CountEnter: counter.In,
			CountExit:  counter.Out,
			DeviceType: "winner",
			DeviceId:   deviceId,
			IpAddress:  "",
			Time:       dateTime,
		}
		allDeviceFlow = append(allDeviceFlow, &flow)
	}
	return allDeviceFlow, nil
}
